package com.imoresoft.magic.service;

import java.util.ArrayList;
import java.util.List;

import com.ambitor.grass.sql.dao.SuperDao;
import com.ambitor.grass.util.data.DataMap;
import com.ambitor.grass.util.data.DatasetList;
import com.ambitor.grass.util.data.IData;
import com.ambitor.grass.util.data.IDataset;
import com.imoresoft.magic.top.TopService;
import com.taobao.api.domain.Item;

public class SyncItemService extends BaseService {

	private TopService topService;

	public SyncItemService(SuperDao superDao, TopService topService) {
		super(superDao);
		this.topService = topService;
	}

	@SuppressWarnings("unchecked")
	public void syncItems(String userId, String nick, String sessionId) {
		IDataset userItemList = new DatasetList();
		List<Item> items = new ArrayList<Item>();
		try {
			IData param = new DataMap();
			param.put("USER_ID", userId);
			userItemList = superDao.queryList("TF_M_USER_ITEM", "iid", param);
			List<String> iids = new ArrayList<String>();
			for (int i = 0; i < userItemList.size(); i++) {
				IData userItem = userItemList.getData(i);
				String iid = userItem.getString("IID");
				iids.add(iid);
			}
			items = topService.getItems(sessionId, nick, iids);
		} catch (Exception e) {
		}

		IDataset newUserItemList = new DatasetList();
		for (Item item : items) {
			IData userItem = new DataMap();
			userItem.put("IID", item.getNumIid());
			userItem.put("USER_ID", userId);
			userItem.put("NICK", nick);
			userItem.put("TITLE", item.getTitle());
			userItem.put("PRICE", item.getPrice());
			userItem.put("PIC_URL", item.getPicUrl());
			newUserItemList.add(userItem);
		}
		try {
			superDao.update("TF_M_USER_ITEM", newUserItemList);
		} catch (Exception e) {
			logger.warn("保存到TF_M_USER_ITEM时出现异常", e);
		}
	}
}
